package com.example.myapplication;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.databinding.ItemUserBinding; // 需与生成的Binding类包名一致
import com.example.myapplication.UserResponse;

import java.util.List;


public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
    private List<UserResponse.User> userList;

    // 构造方法：初始化用户列表
    public UserAdapter(List<UserResponse.User> userList) {
        this.userList = userList;
    }

    // 更新用户列表（下拉刷新/分页加载时调用）
    public void setUserList(List<UserResponse.User> userList) {
        this.userList = userList;
        notifyDataSetChanged(); // 通知列表刷新
    }

    // 1. 创建ViewHolder（加载Item布局）
    @NonNull
    @Override
    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemUserBinding binding = ItemUserBinding.inflate(
                LayoutInflater.from(parent.getContext()),
                parent,
                false
        );
        return new UserViewHolder(binding);
    }

    // 2. 绑定数据到Item布局
    @Override
    public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
        UserResponse.User user = userList.get(position);
        // 直接通过Binding实例绑定数据，避免控件变量冗余
        holder.binding.tvUserId.setText("ID: " + user.getId());
        holder.binding.tvUserName.setText(user.getFirst_name() + " " + user.getLast_name());
        holder.binding.tvUserEmail.setText(user.getEmail());
    }

    // 3. 返回列表项数量
    @Override
    public int getItemCount() {
        return userList != null ? userList.size() : 0;
    }

    // ViewHolder：持有Item布局的Binding实例
    static class UserViewHolder extends RecyclerView.ViewHolder {
        private final ItemUserBinding binding;

        public UserViewHolder(@NonNull ItemUserBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}